import React, { Component } from 'react';
import { observer, inject } from 'mobx-react';
import { withRouter, Route } from 'react-router-dom';
import { Icon, Popover, ActivityIndicator, Bubble, Result, Tools } from 'weaver-mobile';
import { ListViewPage, TabPage, RouteLayout } from 'weaver-mobile-page';
import * as adapter from '../../constants/adapter';
import ContacterCard from '../card/Contacter';
import ContacterForm from '../form/ContacterForm';
import ContacterListStore from '../../stores/list/ContacterListStore';

const Item = Popover.Item;
const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let wrapProps;
if (isIPhone) {
  wrapProps = {
    onTouchStart: e => e.preventDefault(),
  };
}
const isEm = window.em && window.em.checkJsApi('personCardSupport');
const getLabel = Tools.getLabel;
// @inject('contacterListStore')
@withRouter
@observer
export default class ContacterList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      store : new ContacterListStore(),
      overlay: [
        (<Item key="4" value="scan" data-seed="logId">Scan</Item>),
        (<Item key="5" value="special" style={{ whiteSpace: 'nowrap' }}>My Qrcode</Item>),
        (<Item key="6" value="button ct">
          <span style={{ marginRight: 5 }}>Help</span>
        </Item>),
      ],
      span: [7, 1],
      curContacterId: ""
    };
  }

  componentWillMount() {
    const { match, params } = this.props;
    let ps = params ? params : match.params;
    this.state.store.doNew(this, { type: "crm_contacter_normal", ...ps });
  }

  componentDidMount() {
    this.state.store.doInit();
  }

  componentWillUnmount() {
    this.state.store.doClear();
  }

  componentWillReceiveProps(nextProps) {
    const path = this.props.location.pathname;
    //新建联系人页面后退,刷新当前页面
    // if (path.indexOf("createContacterLayout") != -1) {
    //   this.state.store.doSearch();
    // }
  }

  render() {
    const store = this.state.store;
    const { initResponsed, initSuccessed, initFailedMsg } = store;
    if (initResponsed) {
      if (initSuccessed) {
        const { listTab, listTabIndex, listAd, list, showCheck, canEdit, createContacterLayout, contacterCardLayout } = store;
        const { span, overlay, visible, curContacterId } = this.state;
        let tabProps = {
          page: listTabIndex,
          swipeable: true,
          onChange: (tab) => {
            store.topTabChange(tab.key);
          }
        };

        const popoverProps = {
          visible,
          overlay,
          onSelect: this.handleSelect,
          onVisibleChange: this.handleVisibleChange,
        };

        const btns = [];
        if (canEdit) {
          btns.push(<i className={'crm-nav-header-icon icon-crm icon-crm-add'} style={{ color: "#999" }} onClick={this.addContacter.bind(this)} />);
        }

        let getSwipeActionProps = () => ({
          right: [
            {
              text: <i className={'crm-nav-header-icon icon-crm icon-crm-phone'} />,
              onPress: (data) => {
                if (data.mobilephone.length == 11) {
                  this.emTel(data.mobilephone);
                } else {
                  Bubble.warning(getLabel('390903', "请先维护手机号码"), 1, { backgroundColor: adapter.BUBBLE_BGCOLOR }, 2);
                }
              },
              className: "crm-contacter-list-swipe",
            },
            {
              text: <i className={'crm-nav-header-icon icon-crm icon-crm-sms'} />,
              onPress: (data) => {
                if (data.mobilephone.length == 11) {
                  this.emSMS(data.mobilephone,"");
                } else {
                  Bubble.warning(getLabel('390903', "请先维护手机号码"), 1, { backgroundColor: adapter.BUBBLE_BGCOLOR }, 2);
                }
              },
              className: "crm-contacter-list-swipe",
            },
            {
              text: <i className={'crm-nav-header-icon icon-crm icon-crm-email'} />,
              onPress: (data) => {
                if (data.email.indexOf("@") != -1) {
                  this.emMail(data.email);
                } else {
                  Bubble.warning(getLabel('390905', "请先维护邮箱地址"), 1, { backgroundColor: adapter.BUBBLE_BGCOLOR }, 2);
                }
              },
              className: "crm-contacter-list-swipe",
            }
          ],
        })

        return (
          <div>
            <TabPage
              btns={btns}
              span={span}
              tabs={listTab}
              tabProps={tabProps}
              popover={false}
              popoverProps={popoverProps}
            >
            </TabPage>
            <ListViewPage.Normal
              showCheck={false}
              store={list}
              onRowClick={this.onRowClick.bind(this)}
              heightSpace={50}
              withSwipeAction
              swipeActionProps={getSwipeActionProps()}
            />
            <Route
              key={createContacterLayout.id}
              path={createContacterLayout.path}
              render={() => {

                // 添加联系人
                let detailContent = <ContacterForm params={{ operation: "add", customerId: this.props.params.id }} />
                return (
                  <RouteLayout getContainer={() => document.getElementById("root")}>
                    <div
                      key="createContacterLayout"
                      className="wm-route-layout"
                    >
                      {detailContent}
                    </div>
                  </RouteLayout>
                )
              }}
            />
            <Route
              key={contacterCardLayout.id}
              path={contacterCardLayout.path}
              render={() => {
                // 查看联系人
                let detailContent = <ContacterCard params={{ id: curContacterId }} cardStore={store} />
                return (
                  <RouteLayout getContainer={() => document.getElementById("root")}>
                    <div
                      key="contacterCardLayout"
                      className="wm-route-layout"
                    >
                      {detailContent}
                    </div>
                  </RouteLayout>
                )
              }}
            />
          </div>
        );
      } else {
        return (
          <div>
            <Result
              img={<Icon type="cross-circle-o" className="crm_commerce_initFailedMsg" style={{ fill: '#F13642' }} />}
              title=""
              message={initFailedMsg}
            />
          </div>);
      }
    } else {
      return <div className="crm-bg-loading"><ActivityIndicator text="Loading..." /></div>;
    }
  }

  onRowClick(rowData) {
    this.setState({ curContacterId: rowData.id });
    const store = this.state.store;
    const { contacterCardLayout } = store;
    this.props.history.push(contacterCardLayout.path);
  }

  addContacter() {
    const store = this.state.store;
    const { createContacterLayout } = store;
    this.props.history.push(createContacterLayout.path);
  }

  emTel(mobile){
    if(""== mobile){
      return false;
    }      
    if(isEm){
        // console.log("mobile",mobile);
        window.em.tel({'tel':mobile,'success':function (argument) {
          // console.log('success');
          // console.log(JSON.stringify(argument));
        },'fail':function (argument) {
          // console.log('fail')
          // console.log(argument);
        },'cancel':function (argument) {                        
          // console.log('cancel')
          // console.log(argument);
        },'complete':function (argument) {
          // console.log('complete')
          // console.log(argument);
      }});  
    }else{
      window.location.href = `tel:${mobile}`;
    }
  }

  emSMS(mobile,smsContent){
    if(""== mobile){
      return false;
    }
    if(isEm){
        // console.log("mobile",mobile);
        window.em.textMessage({'mobile':mobile,'text':smsContent,'success':function (argument) {
          // console.log('success');
          // console.log(JSON.stringify(argument));
        },'fail':function (argument) {
          // console.log('fail')
          // console.log(argument);
        },'cancel':function (argument) {                        
          // console.log('cancel')
          // console.log(argument);
        },'complete':function (argument) {
          // console.log('complete')
          // console.log(argument);
      }}); 
    }else{
      window.location.href = `sms:${mobile}`;
    }
  }
  
  emMail(mailAddress){
    if(""== mailAddress){
      return false;
    }
    if(isEm){
        // console.log("mailAddress",mailAddress);
        window.em.mailto({'mail':mailAddress,'success':function (argument) {
          // console.log('success');
          // console.log(JSON.stringify(argument));
        },'fail':function (argument) {                        
          // console.log('fail');
          // console.log(argument);
        },'cancel':function (argument) {
          // console.log('cancel');
          // console.log(argument);
        },'complete':function (argument) {
          // console.log('complete');
          // console.log(argument);
      }}); 
    }else{
      window.location.href = `mailto:${mailAddress}`;
    }
  }
}